package com.jx.springcloud;

import com.jx.springcloud.entiy.CommentResult;
import com.jx.springcloud.entiy.User;
import com.jx.springcloud.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class UserControl {
    @Resource
    private UserService userServiceimpl;
    @Value("${server.port}")
    private String port;
    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping(value = "/getUser/{id}")
    public CommentResult getUser(@PathVariable("id") Long id){
            User user = userServiceimpl.getUser(id);
            if(user != null){
                return new CommentResult(200, "查询成功,ServerProt: "+port, user);
            }else{
                return new CommentResult(404, "没有该ID的成员,ServerProt: "+port, null);
            }
    }

    @PostMapping(value = "/insertUser")
    public CommentResult insertUser(@RequestBody User user) {
        System.out.println(user);
        int i = userServiceimpl.insertUser(user);
        if(i>0){
            return  new CommentResult(200, "添加成功,ServerProt: "+port,i);
        }else{
            return new CommentResult(404, "添加失败,ServerProt: "+port,null);
        }
    }

    @GetMapping(value = "/discovery/getmesseges")
    public Object getmesseges(){
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("***************"+service);
        }

        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUND-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.info("--------------"+instance.getUri());
        }
        return this.discoveryClient;
    }

    @GetMapping(value = "/getTimeout")
    public String getPortTimeout(){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return this.port;
    }
}
